package cn.edu.zut.hhr.aspect;

import cn.edu.zut.hhr.annotation.LogAnnotation;
import cn.edu.zut.hhr.entity.User;
import cn.edu.zut.hhr.utils.UserUtil;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

@Component
@Aspect
@Log4j2
public class LogAspectJ {

    @Pointcut("@annotation(cn.edu.zut.hhr.annotation.LogAnnotation)")
    private void pointcut(){};

    /**
     * 抛出个Throwable不用担心,因为代理的方法中可能存在许多异常,因此需要全部抛出(ps:这个记录日志的需要这样,毕竟他不是用来处理异常的)
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("====================log start=====================");
        log.info("module: {}",logAnnotation.module());
        log.info("operator: {}", logAnnotation.operator());
        Class clazz = joinPoint.getTarget().getClass();
        log.info("request method: {}",clazz.getName() + method.getName());
        User user = UserUtil.currentUser();
        if(user != null){
            log.info("username: {}",user.getId().toString());
            log.info("name: {}",user.getName());
        }
        log.info("====================log end======================");
        return joinPoint.proceed();
    }

}
